<template>
  <div class="login-container">
    <h2 class="login-title">登录系统</h2>
    
    <el-form
      ref="loginFormRef"
      :model="loginForm"
      :rules="loginRules"
      label-position="top"
      @keyup.enter="handleLogin"
    >
      <el-form-item prop="username" label="用户名">
        <el-input
          v-model="loginForm.username"
          placeholder="请输入用户名"
          prefix-icon="User"
        ></el-input>
      </el-form-item>
      
      <el-form-item prop="password" label="密码">
        <el-input
          v-model="loginForm.password"
          type="password"
          placeholder="请输入密码"
          prefix-icon="Lock"
          show-password
        ></el-input>
      </el-form-item>
      
      <el-form-item>
        <div class="remember-forgot">
          <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
          <router-link to="/auth/forgot-password" class="forgot-link">忘记密码?</router-link>
        </div>
      </el-form-item>
      
      <el-form-item>
        <el-button
          type="primary"
          :loading="loading"
          class="login-button"
          @click="handleLogin"
        >
          登录
        </el-button>
      </el-form-item>
    </el-form>
    
    <div class="register-link">
      还没有账号? <router-link to="/auth/register">立即注册</router-link>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { User, Lock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { login, getUserInfo } from '@/api/auth'

const router = useRouter()
const route = useRoute()

// 登录表单ref
const loginFormRef = ref(null)

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: '',
  remember: false
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应为3-20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 20, message: '密码长度应为5-20个字符', trigger: 'blur' }
  ]
}

const loading = ref(false)

// 处理登录
const handleLogin = () => {
  if (!loginFormRef.value) return
  
  loginFormRef.value.validate(valid => {
    if (valid) {
      loading.value = true
      
      // 调用登录API
      login(loginForm.username, loginForm.password)
        .then(res => {
          // 保存token
          const { token, tokenHead } = res.data
          localStorage.setItem('token', token)
          
          // 获取用户信息
          return getUserInfo()
        })
        .then(res => {
          const { username, roles, menus } = res.data
          
          // 保存用户信息
          const userInfo = {
            username,
            roles,
            permissions: roles,
            menus
          }
          localStorage.setItem('userInfo', JSON.stringify(userInfo))
          
          // 如果启用了"记住我"，保存用户名
          if (loginForm.remember) {
            localStorage.setItem('rememberedUsername', loginForm.username)
          } else {
            localStorage.removeItem('rememberedUsername')
          }
          
          // 登录成功提示
          ElMessage({
            message: '登录成功',
            type: 'success'
          })
          
          // 重定向到之前尝试访问的页面或默认到仪表盘
          const redirectPath = route.query.redirect || '/'
          router.push(redirectPath)
        })
        .catch(error => {
          console.error('登录失败:', error)
          ElMessage({
            message: '用户名或密码错误',
            type: 'error'
          })
        })
        .finally(() => {
          loading.value = false
        })
    }
  })
}

// 如果有记住的用户名，自动填充
const rememberedUsername = localStorage.getItem('rememberedUsername')
if (rememberedUsername) {
  loginForm.username = rememberedUsername
  loginForm.remember = true
}
</script>

<style scoped>
.login-container {
  width: 100%;
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
  color: #303133;
}

.remember-forgot {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.forgot-link {
  color: #409EFF;
  text-decoration: none;
}

.login-button {
  width: 100%;
}

.register-link {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
  color: #606266;
}

.register-link a {
  color: #409EFF;
  text-decoration: none;
}
</style>
